//
//  AvatarView.m
//  jzyParents
//
//  Created by 任辰东 on 2022/5/1.
//

#import "AvatarView.h"

@interface AvatarView ()
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UIImageView *avatarImageView;

@property (nonatomic, strong) UIImage *placehplderImage;
@end

@implementation AvatarView

-(instancetype)initWithPlaceholderImage:(UIImage *)placehplderImage
{
    self = [super init];
    if (self) {
        _placehplderImage = placehplderImage;
        [self setupViews];
        [self setupLayout];
    }
    return self;
}

- (void)setNameFont:(UIFont *)font
{
    self.nameLabel.font = font;
}

-(void)configViewWithName:(NSString *)name Avatar:(NSString *)avatarUrl
{
    if (!IsEmpty(avatarUrl)) {
        self.avatarImageView.hidden = NO;
        self.nameLabel.hidden = YES;
        [self.avatarImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",avatarUrl]]];
    }else{
        self.avatarImageView.hidden = YES;
        self.nameLabel.hidden = NO;
        if (name.length > 2) {
            NSString *nameStr = [name substringWithRange:NSMakeRange(name.length-2, 2)];
            self.nameLabel.text = nameStr;
        }else{
            self.nameLabel.text = name;
        }
    }
}

-(void)setupViews
{
    self.layer.cornerRadius = 5;
    self.layer.masksToBounds = YES;
    [self addSubview:self.nameLabel];
    [self addSubview:self.avatarImageView];
    self.avatarImageView.image = self.placehplderImage;
}

-(void)setupLayout
{
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.equalTo(self);
    }];
    self.nameLabel.layer.cornerRadius = 5;
    self.nameLabel.layer.masksToBounds = YES;
    
    [self.avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.equalTo(self);
    }];
    self.avatarImageView.layer.cornerRadius = 5;
    self.avatarImageView.layer.masksToBounds = YES;
}

#pragma mark -- lazyload

-(UIImageView *)avatarImageView
{
    if (!_avatarImageView) {
        _avatarImageView = [UIImageView new];
        _avatarImageView.backgroundColor = [UIColor lightGrayColor];
        _avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
        _avatarImageView.clipsToBounds = YES;
    }
    return _avatarImageView;
}

-(UILabel *)nameLabel
{
    if (!_nameLabel) {
        _nameLabel = [UILabel new];
        _nameLabel.backgroundColor = UIColorFromHex(kColorMain);
        _nameLabel.textColor = UIColorFromHex(kColorWhite);
        _nameLabel.font = UIFontSize(13);
        _nameLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _nameLabel;
}

@end
